/* ******************************************** */
/* * Black Scholes Model - Sequential Version * */
/* ******************************************** */

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include "../include/rand.h"

#define MAX(a,b) ((a) > (b) ? a : b)

int main(){

	int i;

	/*Input variables*/
	double s,e,r,sigma,T,m,t;

	/*Output variables*/
	double mean,stddev,confwidth,confmin,confmax;
	
	/*Trials vector*/	
	double *trialVec;

	/*Standard deviation*/
	double sdAuxSum,sdAuxSumSqr,trial;

	double aux = 0;
	
	struct BoxMullerState state;
	initBoxMullerState(&state);

	/*Mean and standard deviation*/
	mean 		= 0;
	sdAuxSum 	= 0;
	sdAuxSumSqr 	= 0;

	/*Initialize seed*/
	srand(time(NULL)*rand());


	/*Read input parameters*/
	scanf("%lf",&s);
	scanf("%lf",&e);
	scanf("%lf",&r);
	scanf("%lf",&sigma);
	scanf("%lf",&T);
	scanf("%lf",&m);

	/*Allocate vector of trials*/
	trialVec = (double *)malloc(m*sizeof(double));

	/*Measure trials*/
	for(i = 0; i < m; i++){
		t = s*exp((r - 0.5*pow(sigma,2))*T + sigma*sqrt(T)*boxMullerRandom(&state));
		aux = t-e;
		trial = exp(-r*T)*MAX(aux,0);
		trialVec[i] = trial;
	}

	/*Calculate standard deviation*/
	for(i = 0; i < m; i++){
		mean += trialVec[i];
		sdAuxSumSqr+= pow(trialVec[i],2);
	}

	/*Calculate mean minimum and maximum confidence*/ 
	sdAuxSum = pow(mean,2);
	stddev = sqrt((m*sdAuxSumSqr - sdAuxSum )/(m*(m-1)));
	confwidth = (1.96*stddev)/sqrt(m);
	mean/=m;
	confmin = mean - confwidth;
	confmax = mean + confwidth;

	/*Free memory*/
	free(trialVec);

	/*Output result*/
	printf("S\t%.0f\nE\t%.0f\nr\t%.0f\nsigma\t%.0f\nT\t%.0f\nM\t%.0f\n",s,e,r,sigma,T,m);
	printf("Confidence interval: (%.4lf, %.4lf)\n",confmin,confmax);

	return 0;
}
